package com.mybatisplus.filters;


import com.mybatisplus.utils.BaseParams;
import com.mybatisplus.utils.ToHttpServletUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@CrossOrigin(value = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE})
@WebFilter(filterName = "SignFilter", urlPatterns = "/sign/*")
public class SignFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String BaseURL = BaseParams.CURRENT_DOMAIN_NAME;//获取url根
        HttpServletRequest httpServletRequest = ToHttpServletUtil.toHttpServletRequest(request);
        String requestURL = httpServletRequest.getRequestURL().toString();//获取请求头的url地址，地址不包含参数！
        if (requestURL.equals(BaseURL + "/sign/sign") && request.getParameter("type").equals("2")) {
            chain.doFilter(request, response);//放行
        } else if (httpServletRequest.getSession(false) != null) {
            chain.doFilter(request, response);//放行
        } else {
            HttpServletResponse httpServletResponse = ToHttpServletUtil.toHttpServletResponse(response);
            httpServletResponse.setHeader("REDIRECT", "REDIRECT");//发送重定向响应头
            httpServletResponse.setHeader("CONTENTPATH", "/");//发送重定向的地址
        }
    }
}
